package com.lingx.web.api.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.service.LingxService;
import com.lingx.service.UserService;
import com.lingx.web.api.IApi;
@Component
public class Api9020 extends AbstractDevApi implements IApi{
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private LingxService lingxService;

	@Resource
	private UserService userService;
	@Override
	public int getApiCode() {
		return 9020;
	}
	@Override
	public String getApiName() {
		return "功能授权";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String roleid=IApi.getParamString(params, "role_id", "");
		String funcid=IApi.getParamString(params, "func_id", "");
		String checked=IApi.getParamString(params, "checked", "");
		String checkedSub=IApi.getParamString(params, "checkedSub", "");
		if("true".equals(checked)&&"false".equals(checkedSub)) {
			if(lingxService.queryForInt("select count(*) from tlingx_role_func where role_id=? and func_id=?", roleid,funcid)==0)
			this.jdbcTemplate.update("insert into tlingx_role_func(id,role_id,func_id)values(uuid(),?,?)",roleid,funcid);
			addSubAuth(funcid,roleid);
		}else if("false".equals(checked)&&"true".equals(checkedSub)) {//||"true".equals(checkedSub)
			if(lingxService.queryForInt("select count(*) from tlingx_role_func where role_id=? and func_id=?", roleid,funcid)==0){
			this.jdbcTemplate.update("insert into tlingx_role_func(id,role_id,func_id)values(uuid(),?,?)",roleid,funcid);
			addSubAuth(funcid,roleid);}
		}else if("false".equals(checked)&&"false".equals(checkedSub)) {//||"false".equals(checkedSub)
			if(lingxService.queryForInt("select count(*) from tlingx_role_func where role_id=? and func_id=?", roleid,funcid)>0){
			this.jdbcTemplate.update("delete from tlingx_role_func where role_id=? and func_id=?",roleid,funcid);
			delSubAuth(funcid,roleid);}
		}
		this.userService.clearAuthCache();
		return ret;
	}

	private void addSubAuth(Object fid,String roleid) {
		List<Map<String,Object>> list=this.jdbcTemplate.queryForList("select id from tlingx_func where fid=?",fid);
		for(Map<String,Object> map:list) {
			if(lingxService.queryForInt("select count(*) from tlingx_role_func where role_id=? and func_id=?", roleid,map.get("id"))==0)
				this.jdbcTemplate.update("insert into tlingx_role_func(id,role_id,func_id)values(uuid(),?,?)",roleid,map.get("id"));
			addSubAuth(map.get("id"),roleid);
		}
	}

	private void delSubAuth(Object fid,String roleid) {
		List<Map<String,Object>> list=this.jdbcTemplate.queryForList("select id from tlingx_func where fid=?",fid);
		for(Map<String,Object> map:list) {
			this.jdbcTemplate.update("delete from tlingx_role_func where role_id=? and func_id=?",roleid,map.get("id"));
			delSubAuth(map.get("id"),roleid);
		}
	}
}
